﻿using Bayantu.Extensions.Common;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Mirco.Extensions.Web;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Mirco.Extensions.Web
{
    public static class FluentValidationExtension
    {
        /// <summary>
        /// 验证返回统一的格式
        /// </summary>
        /// <param name="mvcBuilder"></param>
        public static IMvcBuilder AddFluentValidation(this IMvcBuilder mvcBuilder)
        {
            var assembly = Assembly.Load("Byt.Tpl.models");

            //注册FluentValidation
            mvcBuilder.AddFluentValidation(c => c.RegisterValidatorsFromAssembly(assembly));

            //模型验证 验证失败统一返回格式
            mvcBuilder.Services.Configure<ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {

                    var msg = new Dictionary<string, string>();
                    foreach (var key in context.ModelState.Keys)
                    {
                        var state = context.ModelState[key];
                        var errors = string.Join(",", state.Errors.Select(x => x.ErrorMessage).ToList());
                        msg.Add(key, errors);
                    }

                    var result = BizResult.BusinessFailed(BusinessCodes.FluentValidation, msg.ToJson());
                    return new ObjectResult(result);
                };
            });

            return mvcBuilder;
        }
    }


}
